package com.fansz.FanszAPI.service;

import com.fansz.FanszAPI.domain.IdentityCode;
import com.fansz.FanszAPI.domain.TemporaryUser;
import com.fansz.FanszAPI.utils.Constants;
import com.fansz.FanszAPI.utils.HttpSender;
import com.fansz.FanszAPI.utils.MessageAccount;
import com.fansz.FanszAPI.utils.StringUtils;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by root on 15-10-13.
 */
public class BaseService {

    private static Logger logger = Logger.getLogger(BaseService.class);

    public static String hasRun = "0";

    public static Map<String, String> sessionMap = new HashMap<String, String>();

    public static Map<String, IdentityCode> identityCodeMap = new HashMap<String, IdentityCode>();

    public static Map<String, IdentityCode> identityCodeSendedMap = new HashMap<String, IdentityCode>();

    public static Map<String, TemporaryUser> passwordMap = new HashMap<String, TemporaryUser>();

    public static Map<String, TemporaryUser> passwordSendedMap = new HashMap<String, TemporaryUser>();


    public static void addSession(String sessionId, String timeStamp)
    {
        sessionMap.put(sessionId, timeStamp);
    }

    public static void removeSession(String sessionId)
    {
        sessionMap.remove(sessionId);
    }

    public static boolean containSession(String sessionId)
    {
        return sessionMap.containsKey(sessionId);
    }

    public static void addPassword(String mobile, TemporaryUser user)
    {
        passwordMap.put(mobile, user);
    }

    public static void removePassword(String mobile)
    {
        passwordMap.remove(mobile);
    }

    public static boolean containPassword(String mobile)
    {
        return passwordMap.containsKey(mobile);
    }

    public static TemporaryUser getPassword(String mobile)
    {
        return passwordMap.get(mobile);
    }


    public static void addIdentityCodeSended(String identityCodeSended, IdentityCode code)
    {
        identityCodeSendedMap.put(identityCodeSended, code);
    }

    public static void removeIdentityCodeSended(String identityCodeSended)
    {
        identityCodeSendedMap.remove(identityCodeSended);
    }

    public static boolean containIdentityCodeSended(String identityCodeSended)
    {
        return identityCodeSendedMap.containsKey(identityCodeSended);
    }

    public static IdentityCode getIdentityCodeSended(String identityCodeSended)
    {
        return identityCodeSendedMap.get(identityCodeSended);
    }


    public static void addPasswordSended(String mobile, TemporaryUser user)
    {
        passwordSendedMap.put(mobile, user);
    }

    public static void removePasswordSended(String mobile)
    {
        passwordSendedMap.remove(mobile);
    }

    public static boolean containPasswordSended(String mobile)
    {
        return passwordSendedMap.containsKey(mobile);
    }

    public static TemporaryUser getPasswordSended(String mobile)
    {
        return passwordSendedMap.get(mobile);
    }


    public static void addIdentityCode(String identityCode, IdentityCode code)
    {
        identityCodeMap.put(identityCode, code);
    }

    public static void removeIdentityCode(String identityCode)
    {
        identityCodeMap.remove(identityCode);
    }

    public static boolean containIdentityCode(String identityCode)
    {
        return identityCodeMap.containsKey(identityCode);
    }

    public static IdentityCode getIdentityCode(String identityCode)
    {
        return identityCodeMap.get(identityCode);
    }

    public static void sendMsg()
    {
        logger.info("Start to send message!");
        do {
            sendPassword();
            sendIdentityCode();
        } while (true);
    }

    /**
     *
     * 发送临时密码
     *
     */
    private static void sendPassword()
    {
        String mobile;
        TemporaryUser user;
        int count = 0;
        long curTime;
        int randomNum = StringUtils.getRandomNum();
        String msg = "";
        for (Map.Entry<String, TemporaryUser> m : passwordMap.entrySet())
        {
            try
            {
                if (count == MessageAccount.maxCount)
                {
                    Thread.sleep(1000);
                    count = 0;
                }
                mobile = m.getKey();
                user = m.getValue();

                curTime = System.currentTimeMillis();

                if (curTime - user.getTimeStamp() > MessageAccount.passwordPeriod || user.getCount() > MessageAccount.count)
                {
                    passwordMap.remove(mobile);
                }
                else
                {
                    msg = MessageAccount.passwordMsg;
                    msg = msg.replace("{code}",user.getPassword());
                    msg = msg.replace("{time}",MessageAccount.passwordTime);

                    String returnString = HttpSender.batchSend(MessageAccount.url, MessageAccount.account, MessageAccount.pwd, mobile, msg, false, "", "");

                    logger.info("Send password success : mobile:" + mobile + ",msg : " + msg);

                    if (returnString.endsWith(Constants.SEND_MSG_SUCCESS))
                    {
                        user.setTimeStamp(System.currentTimeMillis());
                        passwordSendedMap.put(mobile, user);
                        passwordMap.remove(mobile);
                    }
                    else
                    {
                        user.setCount(user.getCount() + 1);
                        passwordMap.put(mobile, user);
                    }

                    count++;
                }
            }
            catch (Exception e)
            {
                logger.error(e);
            }
        }
    }


    /**
     *
     * 发送验证码
     *
     */
    private static void sendIdentityCode()
    {
        String mobile;
        IdentityCode identityCode;
        int count = 0;
        long curTime;
        String msg = "";
        for (Map.Entry<String, IdentityCode> m : identityCodeMap.entrySet())
        {
            try
            {
                if (count == MessageAccount.maxCount)
                {
                    Thread.sleep(1000);
                    count = 0;
                }
                mobile = m.getKey();
                identityCode = m.getValue();

                curTime = System.currentTimeMillis();

                if (curTime - identityCode.getTimeStamp() > MessageAccount.identityCodePeriod || identityCode.getCount() > MessageAccount.count)
                {
                    identityCodeMap.remove(mobile);
                }
                else
                {
                    msg = MessageAccount.identityCodeMsg;
                    msg = msg.replace("{code}",identityCode.getIdentityCode());
                    msg = msg.replace("{time}",MessageAccount.passwordTime);

                    String returnString = HttpSender.batchSend(MessageAccount.url, MessageAccount.account, MessageAccount.pwd, mobile, msg, false, "", "");

                    logger.info("Send password success : mobile:" + mobile + ",msg : " + msg);

                    if (returnString.endsWith(Constants.SEND_MSG_SUCCESS))
                    {
                        identityCode.setTimeStamp(System.currentTimeMillis());
                        identityCodeSendedMap.put(mobile, identityCode);
                        identityCodeMap.remove(mobile);
                    }
                    else
                    {
                        identityCode.setCount(identityCode.getCount() + 1);
                        identityCodeMap.put(mobile, identityCode);
                    }

                    count++;
                }
            }
            catch (Exception e)
            {
                logger.error(e);
            }
        }
    }

}
